package com.lefu.es.system;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.FragmentManager;
import android.app.NotificationManager;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lefu.es.blenew.helper.BleHelper1;
import com.lefu.es.cache.CacheHelper;
import com.lefu.es.cache.CacheHelper1;
import com.lefu.es.constant.AppData;
import com.lefu.es.constant.BluetoolUtil;
import com.lefu.es.constant.UtilConstants;
import com.lefu.es.db1.RecordDao;
import com.lefu.es.entity.NutrientBo;
import com.lefu.es.entity.Records;
import com.lefu.es.service.ExitApplication;
import com.lefu.es.service.RecordService;
import com.lefu.es.service.UserService;
import com.lefu.es.system.fragment.MyDialogFragment;
import com.lefu.es.util.LogUtils;
import com.lefu.es.util.MyUtil;
import com.lefu.es.util.SharedPreferencesUtil;
import com.lefu.es.util.StringUtils;
import com.lefu.es.util.ToastUtils;
import com.lefu.es.util.Tool;
import com.lefu.es.util.UtilTooth;
import com.lefu.es.view.GuideView;
import com.lefu.es.view.MyTextView;
import com.lefu.es.view.guideview.HighLightGuideView;
import com.lefu.es.view.kmpautotextview.KMPAutoComplTextView;
import com.wellness.scale.R;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class KitchenScaleActivity1 extends BaseBleActivity implements Runnable, MyDialogFragment.NatureSelectListener {
    private static final String TAG = "KitchenScaleActivity1";
    private static final boolean D = true;
    protected Dialog receiveDataDialog;
    /**
     * 布局点击事件
     */
    View.OnClickListener layoutClickListener = new View.OnClickListener() {
        public void onClick(View v) {
            Intent intent = new Intent();
         /*   intent.setClass(KitchenScaleActivity1.this, RecordKitchenListActivity.class);
            if (null != v.getTag()) {
                intent.putExtra("type", (int) ((Integer) v.getTag()));
            }
            intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            startActivityForResult(intent, 0);*/
            intent.setClass(KitchenScaleActivity1.this, RecordKitchenListActivity.class);
            intent.putExtra("type", UtilConstants.WEIGHT_SINGLE);
            if (null != v.getTag()) {
                intent.putExtra("id", ((Integer) v.getTag()));
            } else {
                intent.putExtra("id", -1);
            }
            intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            startActivityForResult(intent, 0);
        }

        //
    };
    List<Records> rList1 = new ArrayList<>();
    /**
     * 分页框点击事件
     */
    View.OnClickListener imgOnClickListener = new View.OnClickListener() {
        public void onClick(View v) {
            Intent intent = new Intent();
            intent.setClass(KitchenScaleActivity1.this, RecordKitchenListActivity.class);
            intent.putExtra("type", UtilConstants.WEIGHT_SINGLE);
            if (null != v.getTag()) {
                intent.putExtra("id", ((Records) v.getTag()).getId());
            } else {
                intent.putExtra("id", -1);
            }
            intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            startActivityForResult(intent, 0);
        }
    };
    private RecordService recordService;
    private ArrayList<View> views = new ArrayList<View>();
    /**
     * 跳转过来ItemID
     **/
    private int ItemID;
    // private ViewPager pager;
    private TextView norecord_tv;
    private TextView username_tv;
    private UserService uservice;
    private Button infoImg;
    private Button setingImg;
    private Button deletdImg;
    private ImageView headImg;
    private ImageView intentImg;
    private Button unit_btn;
    private Records curRecord;
    private TextView bodywater_tv;
    private TextView bodyfat_tv;
    private TextView bone_tv;
    private TextView musle_tv;
    private TextView visal_tv;
    private TextView bmi_tv;
    private TextView bmr_tv;
    private TextView time_tv;
    private TextView weight_textView17;
    private TextView physicage_tv;
    private TextView scale_connect_state;
    private TextView food_name;
    private KMPAutoComplTextView search_et;
    private ArrayAdapter<String> autoAdapter = null;
    private TextView search_tv;
    private TextView save_tv;
    private int selectedPosition = -1;
    private LinearLayout lineLayout1;
    private LinearLayout lineLayout2;
    private LinearLayout lineLayout3;
    private LinearLayout lineLayout4;
    private LinearLayout lineLayout5;
    private LinearLayout lineLayout7;
    private LinearLayout lineLayout8;
    private LinearLayout linearLayout77;
    private ImageView iv_logo;
    private ImageView leftImg;
    private ImageView rightImg;
    /* 重试次数 */
    private int sendCodeCount = 0;
    private boolean isNotOpenBL = false;
    /* 是否是当前Activity */
    private boolean isCurrentActivoty = true;
    private NutrientBo selectNutrient = null;
    private GuideView guideView;
    private GuideView guideView2;
    private Records receiveRecod;
    private boolean newScale;
    private LayoutInflater inflater;
    private LinearLayout layout_center;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    /* 更新显示内容 */
                    setViews();
                    /* 更新分页内容 */
                    if (CacheHelper.recordListDesc != null && CacheHelper.recordListDesc.size() > 0) {
                        initData(CacheHelper.recordListDesc.get(0));
                    }
                    if (TextUtils.isEmpty(UtilConstants.FIRST_INSTALL_KITCHEN_SCALE) && CacheHelper.recordListDesc.size() > 0) {
                        showTipMask();
                    }
                    break;
                case 1:
                    /* 更新显示内容 */
                    setViews();
                    break;
                case 5:
                    /* 退出 */
                    exit();
                    ExitApplication.getInstance().exit(KitchenScaleActivity1.this);
                    break;
                case UtilConstants.scaleChangeMessage:
                    /* 保存秤类型 */
                    if (UtilConstants.su == null) {
                        UtilConstants.su = new SharedPreferencesUtil(LoadingActivity.mainActivty);
                    }
                    UtilConstants.su.editSharedPreferences("lefuconfig", "scale", UtilConstants.CURRENT_SCALE);
                    /* 保存用户信息 */
                    try {
                        uservice.update(UtilConstants.CURRENT_USER);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    ExitApplication.getInstance().exit(KitchenScaleActivity1.this);
                    Intent intent = new Intent();
                    intent.setClass(KitchenScaleActivity1.this, LoadingActivity.class);
                    KitchenScaleActivity1.this.startActivity(intent);
                    break;
                case 10:
                    Records records = (Records) msg.obj;
                    ToastUtils.ToastCenter(KitchenScaleActivity1.this, "data:" + records.toString());
                    saveData(records);
                    break;
                case 11:
                    if (rList1.size() > 0) rList1.clear();
                    initData(curRecord);
                    break;

            }
        }
    };
    /**
     * 菜单按钮监听
     */
    View.OnClickListener menuBtnOnClickListener = new View.OnClickListener() {
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.info_img_btn:
                    /* 跳转info界面 */
                    if (UtilConstants.CURRENT_SCALE.equals(UtilConstants.KITCHEN_SCALE)) {
                        Intent intent0 = new Intent();
                        intent0.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent0.setClass(KitchenScaleActivity1.this, KitchenInfo1Activity.class);
                        KitchenScaleActivity1.this.startActivity(intent0);
                    } else {
                        Intent intent0 = new Intent();
                        intent0.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent0.setClass(KitchenScaleActivity1.this, InfoActivity.class);
                        KitchenScaleActivity1.this.startActivity(intent0);
                    }
                    break;
                case R.id.seting_img_btn:
                    /* 跳转设置界面 */
                    Intent intent = new Intent();
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setClass(KitchenScaleActivity1.this, SettingActivity.class);
                    KitchenScaleActivity1.this.startActivity(intent);
                    break;
                case R.id.delete_img_btn:

					/* 弹窗删除 */
                    dialog(getString(R.string.deleted_waring), v.getId());
                    break;
            }
        }
    };
    /**
     * 顶部图片点击事件
     */
    View.OnClickListener btnOnClickListener = new View.OnClickListener() {
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.user_header:
                     /* 跳转到用户列表界面 */
                    if (null != mScanner) {
                        mScanner.stopScan();
                    }
                    if (null != mBluetoothLeService) {
                        mBluetoothLeService.disconnect();
                    }
                    /* 跳转到用户列表界面 */
                    Intent intent1 = new Intent();
                    intent1.setClass(KitchenScaleActivity1.this, UserListActivity.class);
                    KitchenScaleActivity1.this.startActivity(intent1);
                    break;
                case R.id.imageView1:
					/* 跳转到链接 */
//					Intent intent2 = new Intent();
//					intent2.setData(Uri.parse(UtilConstants.homeUrl));
//					intent2.setAction(Intent.ACTION_VIEW);
//					KitchenScaleActivity1.this.startActivity(intent2);
                    break;
                case R.id.search_tv:
					/* 搜索 */
                    if (TextUtils.isEmpty(search_et.getText().toString())) {
                        if ("en".equals(MyUtil.getLanguage(KitchenScaleActivity1.this))) {
                            Toast.makeText(KitchenScaleActivity1.this, "Please input something", Toast.LENGTH_SHORT).show();
                        }
                        return;
                    }
                    ArrayList<NutrientBo> nutrientList = CacheHelper1.findNutrientByName(search_et.getText().toString());
                    if (null == nutrientList || nutrientList.size() == 0) {
                        if ("en".equals(MyUtil.getLanguage(KitchenScaleActivity1.this))) {
                            Toast.makeText(KitchenScaleActivity1.this, "No Data had been found", Toast.LENGTH_SHORT).show();
                        }
                        return;
                    }

                    FragmentManager manager = getFragmentManager();
                    MyDialogFragment dialog = MyDialogFragment.newInstance(nutrientList);
                    dialog.show(manager, "dialog");
                    break;
                case R.id.save_tv:
                    LogUtils.d(TAG, "保存数据");
                    if (curRecord != null && null != selectNutrient) {
                        try {
                            List<Records> ls = recordService.findRecordsByScaleTypeAndFoodNameAndKg(UtilConstants.KITCHEN_SCALE, selectNutrient.getNutrientDesc(), curRecord.getRweight());
                            if (null != ls && ls.size() > 0) {

                            } else {
                                curRecord.setRphoto(selectNutrient.getNutrientDesc());
                                if (UtilConstants.CURRENT_USER.getDanwei().equals(UtilConstants.UNIT_FATLB)) {
                                    curRecord.setUnitType(3);
                                } else if (UtilConstants.CURRENT_USER.getDanwei().equals(UtilConstants.UNIT_LB)) {
                                    curRecord.setUnitType(1);
                                } else if (UtilConstants.CURRENT_USER.getDanwei().equals(UtilConstants.UNIT_ML)) {
                                    curRecord.setUnitType(2);
                                } else if (UtilConstants.CURRENT_USER.getDanwei().equals(UtilConstants.UNIT_KG) || UtilConstants.CURRENT_USER.getDanwei().equals(UtilConstants.UNIT_G)) {
                                    curRecord.setUnitType(0);
                                }
                                curRecord = RecordDao.handleKitchenData(recordService, curRecord, selectNutrient);
								/* 重新设置当前记录 */
                                CacheHelper.recordListDesc = recordService.getAllDatasByScaleAndIDDesc(UtilConstants.CURRENT_SCALE, ItemID, UtilConstants.CURRENT_USER.getBheigth());
								/* 刷新界面数据 */
                                handler.sendEmptyMessage(0);
                            }
                        } catch (Exception e1) {
                            e1.printStackTrace();
                        }
                    }
                    break;
                case R.id.unit_btn:
                    LogUtils.d(TAG, "==========点了===unit_btn：" + UtilConstants.CURRENT_USER.getDanwei());
                    try {
                        if (UtilConstants.CURRENT_USER.getDanwei().equals(UtilConstants.UNIT_FATLB)) {
                            UtilConstants.CURRENT_USER.setDanwei(UtilConstants.UNIT_G);
                        } else if (UtilConstants.CURRENT_USER.getDanwei().equals(UtilConstants.UNIT_LB)) {
                            UtilConstants.CURRENT_USER.setDanwei(UtilConstants.UNIT_FATLB);
                        } else if (UtilConstants.CURRENT_USER.getDanwei().equals(UtilConstants.UNIT_ML)) {
                            UtilConstants.CURRENT_USER.setDanwei(UtilConstants.UNIT_LB);
                        } else if (UtilConstants.CURRENT_USER.getDanwei().equals(UtilConstants.UNIT_ML2)) {
                            UtilConstants.CURRENT_USER.setDanwei(UtilConstants.UNIT_ML);
                        } else if (UtilConstants.CURRENT_USER.getDanwei().equals(UtilConstants.UNIT_KG) || UtilConstants.CURRENT_USER.getDanwei().equals(UtilConstants.UNIT_G)) {
                            UtilConstants.CURRENT_USER.setDanwei(UtilConstants.UNIT_ML2);
                        }
                        handler.sendEmptyMessage(0);
                        uservice.update(UtilConstants.CURRENT_USER);
                    } catch (Exception e) {
                        // TODO: handle exception
                    }

                    break;
            }
        }
    };
    private TextView textView1;
    private TextView textView2;
    private Button cancleBtn;
    private Button saveBtn;

    private void showTipMask() {
        HighLightGuideView.builder(this).setText(getString(R.string.kitchen_list_see_data))
                .addNoHighLightGuidView(R.drawable.ic_ok).addHighLightGuidView(layout_center, 0, 0.5f, HighLightGuideView.VIEWSTYLE_CIRCLE)
                .addHighLightGuidView(bodywater_tv, 0, 10f, HighLightGuideView.VIEWSTYLE_OVAL)
                .setTouchOutsideDismiss(false).setOnDismissListener(new HighLightGuideView.OnDismissListener() {
            @Override
            public void onDismiss() {
                if (null == UtilConstants.su) {
                    UtilConstants.su = new SharedPreferencesUtil(KitchenScaleActivity1.this);
                }
                UtilConstants.su.editSharedPreferences("lefuconfig", "first_install_kitchen_scale", "1");
                UtilConstants.FIRST_INSTALL_KITCHEN_SCALE = "1";

            }

        }).show();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_kitchen8);

        recordService = new RecordService(this);
        inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        ItemID = getIntent().getIntExtra("ItemID", 0);
        initView();
        layoutView();
        layout_center = (LinearLayout) findViewById(R.id.layout_center);

        layout_center.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LogUtils.d(TAG, "==========RecordKitchenListActivity===");
                Intent intent = new Intent();
                intent.setClass(KitchenScaleActivity1.this, RecordKitchenListActivity.class);
                if (null != v.getTag()) {
                    intent.putExtra("type", (int) ((Integer) v.getTag()));
                }
                intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                startActivityForResult(intent, 0);
            }
        });

        ExitApplication.getInstance().addActivity(this);

        boolean bindStatus = AppData.checkBindStatus();
        if (!bindStatus && UtilConstants.isFirsShow == 0) {
            bindAltert();
            UtilConstants.isFirsShow = 1;
        }
    }

    @Override
    public void updateConnectionState(int resourceId) {
        switch (resourceId) {
            case R.string.disconnected:
                scale_connect_state.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.darkgray));
                scale_connect_state.setText(getResources().getText(R.string.scale_connect_state_connected));
                break;

            case R.string.connected:
                scale_connect_state.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.darkgray));
                scale_connect_state.setText(getResources().getText(R.string.scale_connect_state_connected));
                break;
        }
    }

    @Override
    public void discoverBleService() {
        ToastUtils.ToastCenter(KitchenScaleActivity1.this, getString(R.string.scale_paired_success));
        //发送人体参数
        if (null != mDeviceName && (mDeviceName.toLowerCase().startsWith("heal"))) {
            try {
                if (null != mBluetoothLeService) {
                    final BluetoothGattCharacteristic characteristic = mBluetoothLeService.getCharacteristicNew(mBluetoothLeService.getSupportedGattServices(), "fff4");
                    mBluetoothLeService.setCharacteristicIndiacate(characteristic, true); //开始监听通道
                    //发送用户组数据
                    String unit = "00";
                    if (UtilConstants.CURRENT_USER.getDanwei().equals(UtilConstants.UNIT_ST)) {
                        unit = "02";
                    } else if (UtilConstants.CURRENT_USER.getDanwei().equals(UtilConstants.UNIT_LB)) {
                        unit = "01";
                    } else {
                        unit = "00";
                    }
                    // 获取用户组
                    String p = UtilConstants.CURRENT_USER.getGroup().replace("P", "0");
                    // 获取 校验位
                    String xor = Integer.toHexString(StringUtils.hexToTen("fd") ^ StringUtils.hexToTen("37") ^ StringUtils.hexToTen(unit) ^ StringUtils.hexToTen(p));
                    Log.e(TAG, "发送新称数据：" + "fd37" + unit + p + "000000000000" + xor);
                    // 发送数据
                    BleHelper1.getInstance().sendDateToScale1(mBluetoothLeService, "fd37" + unit + p + "000000000000" + xor);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (mDeviceName != null && mDeviceName.toLowerCase().startsWith("yu")) {
            try {
                if (null != mBluetoothLeService) {
                    final BluetoothGattCharacteristic characteristic = mBluetoothLeService.getCharacteristicNew(mBluetoothLeService.getSupportedGattServices(), "2a9c");
                    mBluetoothLeService.setCharacteristicIndiacate(characteristic, true); //开始监听通道
                    //发送用户组数据
                    String unit = "00";
                    if (UtilConstants.CURRENT_USER.getDanwei().equals(UtilConstants.UNIT_ST)) {
                        unit = "02";
                    } else if (UtilConstants.CURRENT_USER.getDanwei().equals(UtilConstants.UNIT_LB)) {
                        unit = "01";
                    } else {
                        unit = "00";
                    }
                    // 获取用户组
                    String p = UtilConstants.CURRENT_USER.getGroup().replace("P", "0");
                    // 获取 校验位
                    String xor = Integer.toHexString(StringUtils.hexToTen("fd") ^ StringUtils.hexToTen("37") ^ StringUtils.hexToTen(unit) ^ StringUtils.hexToTen(p));
                    Log.e(TAG, "发送新称数据：" + "fd37" + unit + p + "000000000000" + xor);
                    // 发送数据
                    BleHelper1.getInstance().sendDateToScale(mBluetoothLeService, "fd37" + unit + p + "000000000000" + xor);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            BleHelper1.getInstance().sendDateToScale(mBluetoothLeService, MyUtil.getUserInfo());
        }
    }

    @Override
    public void receiveBleData(String readMessage, String mac, String deviceName) {
        if (!TextUtils.isEmpty(mac)) {
            mDeviceAddress = mac;
        }
        if (!TextUtils.isEmpty(deviceName)) {
            mDeviceName = deviceName;
        }
        //是否为营养秤广播数据
        if (readMessage != null && readMessage.length() == 22 && readMessage.startsWith("ca")) {
            LogUtils.d(TAG, "接收到的是营养秤广播数据" + readMessage);
            caDataShow(readMessage);
        } else {
            LogUtils.d(TAG, "接收到的是其它数据" + readMessage);
            disserview(readMessage);
        }
    }

    @Override
    protected void saveDataCallBack(Records records) {
        saveData(records);
    }

    protected void saveData(Records records) {
        if (records.getScaleType().startsWith(UtilConstants.BATHROOM_SCALE)) {
									/*人体秤*/
            UtilConstants.CURRENT_SCALE = UtilConstants.BATHROOM_SCALE;
            UtilConstants.CURRENT_USER.setScaleType(UtilConstants.CURRENT_SCALE);
            handler.sendEmptyMessage(UtilConstants.scaleChangeMessage);
            recordService.saveOneRecord(records);
        } else if (records.getScaleType().startsWith(UtilConstants.SELECT_SCALE)) {
									/*婴儿秤*/
            UtilConstants.CURRENT_SCALE = UtilConstants.SELECT_SCALE;
            UtilConstants.CURRENT_USER.setScaleType(UtilConstants.CURRENT_SCALE);
            recordService.saveOneRecord(records);
									/*保存测量数据*/
            handler.sendEmptyMessage(UtilConstants.scaleChangeMessage);
        } else if (records.getScaleType().startsWith(UtilConstants.BABY_SCALE)) {
									/* 厨房秤 */
            UtilConstants.CURRENT_SCALE = UtilConstants.BABY_SCALE;
            UtilConstants.CURRENT_USER.setScaleType(UtilConstants.CURRENT_SCALE);
            recordService.saveOneRecord(records);
            handler.sendEmptyMessage(UtilConstants.scaleChangeMessage);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
            /* 是否提示更换称弹窗 */
        //isCurrentActivoty = true;
       /* if (!AppData.hasCheckData) {
            handler.postDelayed(CheckHasDataRunnable, 30 * 1000);
        }*/

		/* 秤识别中 */
        AppData.isCheckScale = false;

		/* 是否重新检测称 */
      /*  if (AppData.reCheck) {
			*//* 跳转到秤检测界面 *//*
            Intent intent1 = new Intent();
            intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent1.setClass(KitchenZhActivity.this, ReCheckActivity.class);
            KitchenZhActivity.this.startActivity(intent1);
            exit();
            ExitApplication.getInstance().exit(this);
        } else {*/
        new Thread(this).start();
           /* if (BluetoolUtil.bleflag) {
                // 再次进入界面后判断是否要重新搜索
                singleton = BlueSingleton.getInstance(handler);
                if (mBluetoothAdapter.isEnabled() && !singleton.getmConnected() && !singleton.getmScanning()) {
                    singleton.scanLeDevice(true, this, mServiceConnection);
                }
            }*/
        //}
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    /**
     * 对营养秤广播数据进行处理
     */
    private void caDataShow(String data) {
        curRecord = MyUtil.parseCAScaleMeaage(data, UtilConstants.CURRENT_USER);
        if (curRecord != null) {
            LogUtils.d(TAG, "营养秤广播数据进行处理:" + curRecord.toString());
            try {
                switch (curRecord.getUnitType()) {
                    case 1:
                        //lb
                        UtilConstants.CURRENT_USER.setDanwei(UtilConstants.UNIT_FATLB);
                        break;
                    case 2:
                        //st
                        break;
                    case 3:
                        //斤
                        break;
                    case 4:
                        //g
                        UtilConstants.CURRENT_USER.setDanwei(UtilConstants.UNIT_G);
                        break;
                    case 5:
                        //lb:oz
                        UtilConstants.CURRENT_USER.setDanwei(UtilConstants.UNIT_FATLB);
                        break;
                    case 6:
                        //oz
                        break;
                    case 7:
                        //ml(water)
                        UtilConstants.CURRENT_USER.setDanwei(UtilConstants.UNIT_ML);
                        break;
                    case 8:
                        //ml（milk）
                        UtilConstants.CURRENT_USER.setDanwei(UtilConstants.UNIT_ML2);

                        break;
                    case 0:
                        break;
                    default:
                        UtilConstants.CURRENT_USER.setDanwei(UtilConstants.UNIT_G);
                        break;

                }
                handler.sendEmptyMessage(11);
              /*  Message message = new Message();
                message.obj = receiveRecord;*/
                //uservice.update(UtilConstants.CURRENT_USER);
            } catch (Exception e) {
                // TODO: handle exception
            }
        }
    }

    /**
     * 处理称发过来的数据
     *
     * @param readMessage
     */
    private void disserview(String readMessage) {
        System.out.println("===========收到数据：" + readMessage);
        if (TextUtils.isEmpty(readMessage)) {
            return;
        }

        LogUtils.i(TAG, "==UtilConstants.CURRENT_USER:" + UtilConstants.CURRENT_USER.toString());
        if (readMessage.startsWith("cb") || readMessage.startsWith("ca")) {

        } else {
            if (UtilConstants.CURRENT_USER.getAgeYear() < 10 || UtilConstants.CURRENT_USER.getBheigth() < 100) {
                if (UtilConstants.CURRENT_USER.getDanwei().equals(UtilConstants.UNIT_KG)) {
                    Toast.makeText(KitchenScaleActivity1.this, getString(R.string.age_error_4), Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(KitchenScaleActivity1.this, getString(R.string.age_error_6), Toast.LENGTH_SHORT).show();
                }
                return;
            }
        }
        newScale = false;
        /** 称类型判断 */
        String choice_scale = "";
        if ((readMessage.toLowerCase().startsWith(UtilConstants.BODY_SCALE))) {
            choice_scale = UtilConstants.BODY_SCALE;
        } else if ((readMessage.toLowerCase().startsWith(UtilConstants.BATHROOM_SCALE))) {
            choice_scale = UtilConstants.BATHROOM_SCALE;
        } else if ((readMessage.toLowerCase().startsWith(UtilConstants.BABY_SCALE))) {
            choice_scale = UtilConstants.BABY_SCALE;
        } else if ((readMessage.toLowerCase().startsWith(UtilConstants.KITCHEN_SCALE))) {
            choice_scale = UtilConstants.KITCHEN_SCALE;
        }
        UtilConstants.CURRENT_SCALE = choice_scale;
        String deviceName = BluetoolUtil.mConnectedDeviceName;
        LogUtils.i(TAG, "==========deviceName" + deviceName);
        if (readMessage != null && readMessage.length() == 40) {
            readMessage = readMessage.substring(0, 22);
            LogUtils.d(TAG, "=====sub后的：" + readMessage);
        }

        if ((null != mDeviceName && mDeviceName.toLowerCase().startsWith(UtilConstants.DLscaleName)
                || null != mDeviceName && mDeviceName.toLowerCase().startsWith("heal")
        ) && readMessage.length() == "ce00005c03000000000091".length()) {  //新的DL Scale
            // /CF 88 13 00 14 00 00 00 00 00 40
            if (com.lefu.es.db.RecordDao.isLockData(readMessage)) {
                if ((System.currentTimeMillis() - UtilConstants.receiveDataTime > 1500)) {
                    LogUtils.i(TAG, "===============锁定了数据>>：" + readMessage);
                    UtilConstants.receiveDataTime = System.currentTimeMillis();
                    dueDate1(readMessage, 3);
                }
            } else {
                LogUtils.i(TAG, "============1过程数据：" + readMessage);
                //  dueDate1(readMessage, 2);
            }

        } else {
            System.out.println("读取到数据：" + readMessage);
            if (readMessage.startsWith("cb") || readMessage.startsWith("ca")) {
                if (readMessage.equals(UtilConstants.ERROR_CODE)) {
                    if (sendCodeCount < 1) {
                        if (mBluetoothLeService != null)
                            send_Data(MyUtil.getUserInfo());
                        sendCodeCount++;
                    } else {
                        Toast.makeText(KitchenScaleActivity1.this, getString(R.string.user_data_error), Toast.LENGTH_LONG).show();
                        //Toast.makeText(KitchenScaleActivity1.this, getString(R.string.user_data_error), Toast.LENGTH_LONG).show();
                    }
                } else if (readMessage.equals(UtilConstants.ERROR_CODE_TEST)) {
                    Toast.makeText(KitchenScaleActivity1.this, getString(R.string.scale_measurement_error), Toast.LENGTH_SHORT).show();
                }
            }

            /** 判断是不是两次连续的数据 */
            if (System.currentTimeMillis() - UtilConstants.receiveDataTime < 1000) {
                return;
            }
            UtilConstants.receiveDataTime = System.currentTimeMillis();
                /* 判断称类型是否错误 */
            if (readMessage.startsWith(UtilConstants.KITCHEN_SCALE)) {
                dueDate(readMessage);
            } else {
                if (readMessage.length() > 31) {
                        /* 跳转到制定的秤界面 */
                    if (readMessage.startsWith(UtilConstants.BATHROOM_SCALE)) {
                            /* 人体秤 */
                        UtilConstants.CURRENT_SCALE = UtilConstants.BATHROOM_SCALE;
                    } else if (readMessage.startsWith(UtilConstants.BABY_SCALE)) {
                            /* 婴儿秤 */
                        UtilConstants.CURRENT_SCALE = UtilConstants.BABY_SCALE;
                    } else if (readMessage.startsWith(UtilConstants.BODY_SCALE)) {
                            /*脂肪秤*/
                        UtilConstants.CURRENT_SCALE = UtilConstants.BODY_SCALE;
                    }
                    UtilConstants.CURRENT_USER.setScaleType(UtilConstants.CURRENT_SCALE);
                        /* 保存测量数据 */
                    RecordDao.dueDate(recordService, readMessage);
                    handler.sendEmptyMessage(UtilConstants.scaleChangeMessage);
                } else if (readMessage.equals(UtilConstants.ERROR_CODE_GETDATE)) {
                    openErrorDialog("2");
                }
            }
        }
    }

    /**
     * 初始化测量记录分页
     *//*
    private void Init(List<Records> rList) {
        if (null == views) {
            views = new ArrayList<View>();
        } else {
            views.clear();
        }
        if (null != rList && rList.size() > 0) {
            weight_textView17.setVisibility(View.GONE);
            rightImg.setVisibility(View.VISIBLE);
            leftImg.setVisibility(View.VISIBLE);
            if (rList.size() > 1) {
                this.rightImg.setImageDrawable(getResources().getDrawable(R.drawable.arrowright_white));
            }
            norecord_tv.setVisibility(View.INVISIBLE);

            LayoutInflater mLi = LayoutInflater.from(this);
            View view0 = mLi.inflate(R.layout.nullwhats, null);
            views.add(view0);
            for (Records record : rList) {
                View vie = creatView(record, null);
                views.add(vie);
            }
            View view00 = mLi.inflate(R.layout.nullwhats, null);
            views.add(view00);
            try {
                adapter = new MyPageAdapter(views);
                pager.setAdapter(adapter);
                adapter.notifyDataSetChanged();
                pager.setCurrentItem(1);
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else {
            leftImg.setImageDrawable(getResources().getDrawable(R.drawable.left_to));
            rightImg.setImageDrawable(getResources().getDrawable(R.drawable.right_to));
            weight_textView17.setVisibility(View.GONE);
            rightImg.setVisibility(View.INVISIBLE);
            leftImg.setVisibility(View.INVISIBLE);
            norecord_tv.setVisibility(View.INVISIBLE);
            adapter = new MyPageAdapter(views);
            pager.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        }
    }*/

    /**
     * 数据处理
     *
     * @param readMessage
     * @param i
     */
    private void dueDate1(String readMessage, int i) {
        LogUtils.i(TAG, "==========readMessage====i" + i);
        if (0 == i) {//旧秤
            receiveRecod = MyUtil.parseMessage(this.recordService, readMessage);
            Message msg1 = handler.obtainMessage(3);
            msg1.obj = receiveRecod;
            handler.sendMessage(msg1);
        } else if (1 == i) {//阿里秤
            receiveRecod = MyUtil.parseZuKangMeaage(this.recordService, readMessage, UtilConstants.CURRENT_USER);
            Message msg1 = handler.obtainMessage(3);
            msg1.obj = receiveRecod;
            handler.sendMessage(msg1);
        } else if (2 == i) {//新称过程数据
            LogUtils.i(TAG, "=====新称过程数据========");
            //MyUtil.setProcessWeightData(BabyScaleActivity.this,readMessage,weithValueTx,UtilConstants.CURRENT_USER.getDanwei(),false);
            // weithValueTx.setTexts(UtilTooth.keep1Point(weight),null);
        } else if (3 == i) {//新秤锁定数据
            receiveRecod = MyUtil.parseDLScaleMessage(KitchenScaleActivity1.this.recordService, readMessage, UtilConstants.CURRENT_USER);
            if (null != receiveRecod) {
                receiveRecod.setReceiveMsg(readMessage);
            }
            Message msg1 = new Message();
            msg1.what = 10;
            msg1.obj = receiveRecod;
            LogUtils.i(TAG, "=====新秤锁定数据=ppp======" + receiveRecod.toString());
            handler.sendMessage(msg1);
        }
    }

    /**
     * 发送数据
     */
    private void send_Data(String data) {
        if (TextUtils.isEmpty(data)) return;
        sendDateToScale(data);
        try {
            Thread.sleep(500);

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        sendDateToScale(data);
    }

    /**
     * 处理数据
     */
    public synchronized void dueDate(String message) {
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("duedate", message);
        Records recod = MyUtil.parseMessage(this.recordService, message);
        if (recod != null && null != recod.getScaleType() && recod.getScaleType().equalsIgnoreCase(UtilConstants.CURRENT_SCALE)) {
            if (TextUtils.isEmpty(food_name.getText())) {
                selectNutrient = null;
            } else {
                if (null != selectNutrient) recod.setRphoto(selectNutrient.getNutrientDesc());
            }
            if (recod.getUgroup() != null) {
                int ugroup = Integer.parseInt(recod.getUgroup().replace("P", ""));
                if (ugroup < 10) {
                    Bundle mBundle = new Bundle();
                    mBundle.putSerializable("record", recod);
                    intent.putExtras(mBundle);
                    intent.setClass(getApplicationContext(), ReceiveAlertActivity.class);
                    startActivity(intent);
                }
            }
        }
    }

    private void sendDateToScale(String data) {
        //System.out.println("发送数据=" + MyUtil.getUserInfo());
        final BluetoothGattCharacteristic characteristic2 = mBluetoothLeService.getCharacteristic(mBluetoothLeService.getSupportedGattServices(), "fff4");
        if (characteristic2 != null) {
            mBluetoothLeService.setCharacteristicNotification(characteristic2, true);
        }

        try {
            Thread.sleep(500);

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        final BluetoothGattCharacteristic characteristic = mBluetoothLeService.getCharacteristic(mBluetoothLeService.getSupportedGattServices(), "fff1");
        if (characteristic != null) {
            final byte[] dataArray = StringUtils.hexStringToByteArray(data);
            characteristic.setValue(dataArray);
            mBluetoothLeService.writeCharacteristic(characteristic);
            characteristic.getProperties();
        }
    }

    /**
     * 初始化视图
     */
    private void initView() {
        try {
            uservice = new UserService(this);
            weight_textView17 = (TextView) this.findViewById(R.id.weight_textView17);
            norecord_tv = (TextView) this.findViewById(R.id.norecord_textView);
            username_tv = (TextView) this.findViewById(R.id.username_tv);
            //compare_tv = (MyTextView2) this.findViewById(R.id.compare_tv);
            //targetv = (MyTextView2) this.findViewById(R.id.targetv);

			/* 称单位 */
            if (null != UtilConstants.su) {
                UtilConstants.CHOICE_KG = (String) UtilConstants.su.readbackUp("lefuconfig", "unit", UtilConstants.UNIT_KG);
            }

//			if (null != UtilConstants.CURRENT_USER) {
//				compare_tv.setTexts("0.0" + UtilConstants.CURRENT_USER.getDanwei(), null);
//			}

			/* 文本内容 */
            bodywater_tv = (TextView) this.findViewById(R.id.textView2);
            bodyfat_tv = (TextView) this.findViewById(R.id.textView4);
            bone_tv = (TextView) this.findViewById(R.id.textView6);
            bmi_tv = (TextView) this.findViewById(R.id.textView14);
            visal_tv = (TextView) this.findViewById(R.id.textView10);
            musle_tv = (TextView) this.findViewById(R.id.textView8);
            bmr_tv = (TextView) this.findViewById(R.id.textView12);
            time_tv = (TextView) this.findViewById(R.id.textView19);
            physicage_tv = (TextView) this.findViewById(R.id.textView74);
            //tvBmi = (TextView) this.findViewById(R.id.tv_guide_value);
            scale_connect_state = (TextView) this.findViewById(R.id.scale_connect_state);

            food_name = (TextView) this.findViewById(R.id.food_name);
            search_et = (KMPAutoComplTextView) this.findViewById(R.id.search_et);
            search_tv = (TextView) this.findViewById(R.id.search_tv);
            save_tv = (TextView) this.findViewById(R.id.save_tv);
            /* 按钮 */
            infoImg = (Button) this.findViewById(R.id.info_img_btn);
            setingImg = (Button) this.findViewById(R.id.seting_img_btn);
            deletdImg = (Button) this.findViewById(R.id.delete_img_btn);
            headImg = (ImageView) this.findViewById(R.id.user_header);
            intentImg = (ImageView) this.findViewById(R.id.imageView1);
            leftImg = (ImageView) this.findViewById(R.id.imageView2);
            rightImg = (ImageView) this.findViewById(R.id.imageView3);
            unit_btn = (Button) this.findViewById(R.id.unit_btn);

            //  pager = (ViewPager) this.findViewById(R.id.weight_contains);
            /* 监听 */
            infoImg.setOnClickListener(menuBtnOnClickListener);
            deletdImg.setOnClickListener(menuBtnOnClickListener);
            setingImg.setOnClickListener(menuBtnOnClickListener);
            headImg.setOnClickListener(btnOnClickListener);
            intentImg.setOnClickListener(btnOnClickListener);
            search_tv.setOnClickListener(btnOnClickListener);
            save_tv.setOnClickListener(btnOnClickListener);
            unit_btn.setOnClickListener(btnOnClickListener);

            LogUtils.d(TAG, "================CacheHelper1.nutrientTempNameList:" + CacheHelper1.nutrientTempNameList.size());

            search_et.setDatas(CacheHelper1.nutrientTempNameList);
            search_et.inputTextNull(food_name, selectNutrient);
            /*设置自动搜索提示*/
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    if (null != CacheHelper1.nutrientNameList && CacheHelper1.nutrientNameList.size() > 0)
                        search_et.setDatas(CacheHelper1.nutrientNameList);
                }
            }, 5000);
            search_et.setOnPopupItemClickListener(new KMPAutoComplTextView.OnPopupItemClickListener() {
                @Override
                public void onPopupItemClick(CharSequence charSequence) {
                    //查找
                    if (TextUtils.isEmpty(charSequence)) {
                        return;
                    }
                    LogUtils.d(TAG, "查找的String" + charSequence.toString());
                    NutrientBo nutrient = CacheHelper1.queryNutrientsByName(charSequence.toString());
                    if (null == nutrient) {
                        if ("en".equals(MyUtil.getLanguage(KitchenScaleActivity1.this))) {
                            Toast.makeText(KitchenScaleActivity1.this, "No Data had been found", Toast.LENGTH_SHORT).show();
                        }
                        return;
                    }
                    search_et.setText(nutrient.getNutrientDesc());
                    selectNutrient = nutrient;
                    natureSelectComplete(nutrient);
                }
            });
            /* 分页显示测量记录 */

            //pager.bringToFront();
    /*        pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageSelected(int arg0) {
                    if (null != views && views.size() > 0) {
                        if (arg0 == views.size() - 1 || arg0 == 0) {
                            if (arg0 == 0) {
                                pager.setCurrentItem(arg0 + 1);
                            } else {
                                pager.setCurrentItem(arg0 - 1);
                            }
                        } else {
                            if (arg0 > 0) {
                                selectedPosition = arg0 - 1;
                            } else {
                                selectedPosition = 0;
                            }
                            curRecord = CacheHelper.recordListDesc.get(selectedPosition);
                            handler.sendEmptyMessage(1);
                        }

                        if (pager.getCurrentItem() < 2) {
                            leftImg.setImageDrawable(getResources().getDrawable(R.drawable.left_to));
                        } else {
                            leftImg.setImageDrawable(getResources().getDrawable(R.drawable.arrowleft_white));
                        }
                        if (pager.getCurrentItem() >= (views.size() - 2)) {
                            rightImg.setImageDrawable(getResources().getDrawable(R.drawable.right_to));
                        } else {
                            rightImg.setImageDrawable(getResources().getDrawable(R.drawable.arrowright_white));
                        }
                    } else {
                        leftImg.setImageDrawable(getResources().getDrawable(R.drawable.left_to));
                    }
                }

                @Override
                public void onPageScrolled(int arg0, float arg1, int arg2) {
                }

                @Override
                public void onPageScrollStateChanged(int arg0) {
                }
            });*/
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }

    }

    /**
     * 初始化布局
     */
    private void layoutView() {
        lineLayout1 = (LinearLayout) this.findViewById(R.id.linearLayout1);
        lineLayout2 = (LinearLayout) this.findViewById(R.id.linearLayout2);
        lineLayout3 = (LinearLayout) this.findViewById(R.id.linearLayout3);
        lineLayout4 = (LinearLayout) this.findViewById(R.id.linearLayout4);
        lineLayout5 = (LinearLayout) this.findViewById(R.id.linearLayout5);
        lineLayout7 = (LinearLayout) this.findViewById(R.id.linearLayout7);
        lineLayout8 = (LinearLayout) this.findViewById(R.id.linearLayout8);
        linearLayout77 = (LinearLayout) this.findViewById(R.id.linearLayout77);
        lineLayout1.setTag(UtilConstants.BODYWATER_SINGLE);
        lineLayout2.setTag(UtilConstants.BODYFAT_SINGLE);
        lineLayout3.setTag(UtilConstants.BMI_SINGLE);
        lineLayout4.setTag(UtilConstants.BONE_SINGLE);
        lineLayout5.setTag(UtilConstants.VISCALEFAT_SINGLE);
        lineLayout7.setTag(UtilConstants.MUSCALE_SINGLE);
        lineLayout8.setTag(UtilConstants.BMR_SINGLE);
        linearLayout77.setTag(UtilConstants.PHSICALAGE_SINGLE);
        //linearLayout77.setVisibility(View.GONE);

        lineLayout1.setOnClickListener((View.OnClickListener) layoutClickListener);
        lineLayout2.setOnClickListener((View.OnClickListener) layoutClickListener);
        lineLayout3.setOnClickListener((View.OnClickListener) layoutClickListener);
        lineLayout4.setOnClickListener((View.OnClickListener) layoutClickListener);
        lineLayout5.setOnClickListener((View.OnClickListener) layoutClickListener);
        lineLayout7.setOnClickListener((View.OnClickListener) layoutClickListener);
        lineLayout8.setOnClickListener((View.OnClickListener) layoutClickListener);
        linearLayout77.setOnClickListener((View.OnClickListener) layoutClickListener);
    }

    /**
     * 绑定提示
     */
    private void bindAltert() {
        // 初始化自定义布局参数
        LayoutInflater layoutInflater = getLayoutInflater();
        // 为了能在下面的OnClickListener中获取布局上组件的数据，必须定义为final类型.
        View customLayout = layoutInflater.inflate(R.layout.activity_receive_alert2, (ViewGroup) findViewById(R.id.receiveDataDialog));
        cancleBtn = (Button) customLayout.findViewById(R.id.cancle_datacbtn);
        saveBtn = (Button) customLayout.findViewById(R.id.save_databtn);
        textView1 = (TextView) customLayout.findViewById(R.id.textView1);
        textView2 = (TextView) customLayout.findViewById(R.id.textView2);
        textView1.setText(R.string.bind_tishi_4);
        textView2.setText(R.string.bind_tishi_1);
        cancleBtn.setText(R.string.no_btn);
        saveBtn.setText(R.string.yes_btn);

        cancleBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                receiveDataDialog.dismiss();
            }
        });
        saveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                receiveDataDialog.dismiss();
                Intent intent = new Intent(KitchenScaleActivity1.this, BindScaleActivity.class);
                startActivity(intent);
            }
        });
        receiveDataDialog = new Dialog(this, R.style.dialog);
        receiveDataDialog.setContentView(customLayout);
        receiveDataDialog.show();
        Window window = receiveDataDialog.getWindow();
        window.setGravity(Gravity.CENTER); // 此处可以设置dialog显示的位置
        window.setWindowAnimations(R.style.mystyle); // 添加动画
    }

    /**
     * 选择了营养类型
     **/
    @Override
    public void natureSelectComplete(NutrientBo nutrient) {
        if (null != nutrient) {
            //重绘界面参数
            food_name.setText(nutrient.getNutrientDesc());
            selectNutrient = nutrient;
            if (null != curRecord) {
                float calcium = 0.0f;
                if (!TextUtils.isEmpty(nutrient.getNutrientCalcium()) && Tool.isDigitsOnly(nutrient.getNutrientCalcium())) {
                    calcium = Float.parseFloat(nutrient.getNutrientCalcium()) * curRecord.getRweight() * 0.01f;//钙
                }
                float protein = 0.0f;
                if (!TextUtils.isEmpty(nutrient.getNutrientProtein()) && Tool.isDigitsOnly(nutrient.getNutrientProtein())) {
                    protein = Float.parseFloat(nutrient.getNutrientProtein()) * curRecord.getRweight() * 0.01f;//蛋白质
                }
                float kcal = 0.0f;
                if (!TextUtils.isEmpty(nutrient.getNutrientEnerg()) && Tool.isDigitsOnly(nutrient.getNutrientEnerg())) {
                    kcal = Float.parseFloat(nutrient.getNutrientEnerg()) * curRecord.getRweight() * 0.01f;//卡路里
                }
                float water = 0.0f;
                if (!TextUtils.isEmpty(nutrient.getNutrientCarbohydrt()) && Tool.isDigitsOnly(nutrient.getNutrientCarbohydrt())) {
                    water = Float.parseFloat(nutrient.getNutrientCarbohydrt()) * curRecord.getRweight() * 0.01f;//碳水化合物
                }
                float fat = 0.0f;
                if (!TextUtils.isEmpty(nutrient.getNutrientLipidTot()) && Tool.isDigitsOnly(nutrient.getNutrientLipidTot())) {
                    fat = Float.parseFloat(nutrient.getNutrientLipidTot()) * curRecord.getRweight() * 0.01f;//脂肪
                }
                float fibre = 0.0f;
                if (!TextUtils.isEmpty(nutrient.getNutrientFiberTD()) && Tool.isDigitsOnly(nutrient.getNutrientFiberTD())) {
                    fibre = Float.parseFloat(nutrient.getNutrientFiberTD()) * curRecord.getRweight() * 0.01f;//纤维
                }
                float cholesterol = 0.0f;
                if (!TextUtils.isEmpty(nutrient.getNutrientCholestrl()) && Tool.isDigitsOnly(nutrient.getNutrientCholestrl())) {
                    cholesterol = Float.parseFloat(nutrient.getNutrientCholestrl()) * curRecord.getRweight() * 0.01f;//胆固醇
                }
                float vitaminC = 0.0f;
                if (!TextUtils.isEmpty(nutrient.getNutrientVitB6()) && Tool.isDigitsOnly(nutrient.getNutrientVitB6())) {
                    vitaminC = Float.parseFloat(nutrient.getNutrientVitB6()) * curRecord.getRweight() * 0.01f;//维生素C
                }

                bodywater_tv.setText(UtilTooth.keep2Point(kcal) + "kcal"); //卡路里
                bodyfat_tv.setText(UtilTooth.keep2Point(protein) + "g");//蛋白质
                bone_tv.setText(UtilTooth.keep2Point(fat) + "g"); //脂肪
                musle_tv.setText(UtilTooth.keep2Point(water) + "g");//碳水化合物
                visal_tv.setText(UtilTooth.keep2Point(fibre) + "g");//纤维
                bmr_tv.setText(UtilTooth.keep2Point(cholesterol) + "mg");//胆固醇
                bmi_tv.setText(UtilTooth.keep2Point(vitaminC) + "mg");//维生素C
                physicage_tv.setText(UtilTooth.keep2Point(calcium) + "mg");//钙
            }
        }
    }

    /**
     * 设置视图数据
     */
    private void setViews() {
        /* 当前用户不为空 */
        if (UtilConstants.CURRENT_USER != null) {
            /* 用户姓名 */
            this.username_tv.setText(UtilConstants.CURRENT_USER.getUserName());
			/* 设置用户头像 */
            if (null != UtilConstants.CURRENT_USER.getPer_photo() && !"".equals(UtilConstants.CURRENT_USER.getPer_photo()) && !UtilConstants.CURRENT_USER.getPer_photo().equals("null")) {
                headImg.setImageURI(Uri.fromFile(new File(UtilConstants.CURRENT_USER.getPer_photo())));
            } else {
                if ("1".equals(UtilConstants.CURRENT_USER.getSex())) {
                    headImg.setImageResource(R.drawable.nan);
                } else {
                    headImg.setImageResource(R.drawable.nu);
                }

            }
        }

		/* 是否有测量记录 */
        if (curRecord != null) {
            Date iDate = UtilTooth.stringToTime(curRecord.getRecordTime());
            if (iDate != null) {
                if ("zh".equals(MyUtil.getLanguage(this))) {
                    time_tv.setText(StringUtils.getDateStringZh(iDate, 5));
                } else if ("en".equals(MyUtil.getLanguage(this))) {
                    time_tv.setText(StringUtils.getDateString(iDate, 5));
                } else if ("fr".equals(MyUtil.getLanguage(this))) {
                    time_tv.setText(StringUtils.getDateStringFr(iDate, 5));
                } else if ("de".equals(MyUtil.getLanguage(this))) {
                    time_tv.setText(StringUtils.getDateStringDe(iDate, 5));
                } else if ("es".equals(MyUtil.getLanguage(this))) {
                    time_tv.setText(StringUtils.getDateStringEs(iDate, 5));
                } else if ("it".equals(MyUtil.getLanguage(this))) {
                    time_tv.setText(StringUtils.getDateStringIt(iDate, 5));
                } else if ("ja".equals(MyUtil.getLanguage(this))) {
                    time_tv.setText(StringUtils.getDateStringJa(iDate, 5));
                } else {
                    time_tv.setText(StringUtils.getDateString(iDate, 5));
                }
            }
            bodywater_tv.setText(UtilTooth.keep2Point(curRecord.getRbodywater()) + "kcal"); //卡路里
            bodyfat_tv.setText(UtilTooth.keep2Point(curRecord.getRbodyfat()) + "g");//蛋白质
            bone_tv.setText(UtilTooth.keep2Point(curRecord.getRbone()) + "g"); //脂肪
            musle_tv.setText(UtilTooth.keep2Point(curRecord.getRmuscle()) + "g");//碳水化合物
            visal_tv.setText(UtilTooth.keep2Point(curRecord.getRvisceralfat()) + "g");//纤维
            bmr_tv.setText(UtilTooth.keep2Point(curRecord.getRbmi()) + "mg");//胆固醇
            bmi_tv.setText(UtilTooth.keep2Point(curRecord.getRbmr()) + "mg");//维生素C
            physicage_tv.setText(UtilTooth.keep2Point(curRecord.getBodyAge()) + "mg");//钙
        } else {
			/* 无测量记录 */
            bodywater_tv.setText("0.0kcal");
            bodyfat_tv.setText("0.0g");
            bone_tv.setText("0.0g");
            musle_tv.setText("0.0g");
            visal_tv.setText("0.0g");
            bmi_tv.setText("0.0mg");
            bmr_tv.setText("0.0mg");
            //tvBmi.setText("0.0g");
            physicage_tv.setText("0.0mg");
        }
    }    @Override
    public void run() {
        if (ItemID != 0) {
            try {
                UtilConstants.CURRENT_USER = this.uservice.find(ItemID);
                CacheHelper.recordListDesc = this.recordService.getAllDatasByScaleAndIDDesc(UtilConstants.CURRENT_SCALE, ItemID, 167f);
                if (null != CacheHelper.recordListDesc && CacheHelper.recordListDesc.size() > 0) {
                    curRecord = CacheHelper.recordListDesc.get(0);
                } else {
                    curRecord = null;
                }
                handler.sendEmptyMessage(0);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 弹窗
     */
    protected void dialog(String title, final int id) {
        AlertDialog.Builder builder = new AlertDialog.Builder(KitchenScaleActivity1.this);
        builder.setMessage(title);
        builder.setNegativeButton(R.string.cancle_btn, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }

        });
        builder.setPositiveButton(R.string.ok_btn, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                try {
                    switch (id) {
                        case R.id.delete_img_btn:
							/* 删除当前记录 */
                            if (null != curRecord) {
                                recordService.delete(curRecord);
                            }
							/* 重新设置当前记录 */
                            CacheHelper.recordListDesc = recordService.getAllDatasByScaleAndIDDesc(UtilConstants.CURRENT_SCALE, ItemID, UtilConstants.CURRENT_USER.getBheigth());
                            if (null != CacheHelper.recordListDesc && CacheHelper.recordListDesc.size() > 0) {
                                curRecord = CacheHelper.recordListDesc.get(0);
                            } else {
                                curRecord = null;
                            }
							/* 刷新界面数据 */
                            handler.sendEmptyMessage(0);
                            break;
                        default:
                    }
                } catch (Exception e) {
                }
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            handler.sendEmptyMessage(5);
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_HOME) {
            exit();
            ExitApplication.getInstance().exit(this);
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 退出
     */
    private void exit() {
		/* 停止服务 */
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancel(0);
        if (null != LoadingActivity.mainActivty) {
            LoadingActivity.mainActivty.finish();
        }
        KitchenScaleActivity1.this.finish();
    }

    /**
     * 初始化测量记录分页
     */
    private void initData(Records record) {
        LogUtils.d(TAG, "初始化测量记录分页111111");
        LayoutInflater mLi = LayoutInflater.from(this);
        weight_textView17.setVisibility(View.GONE);
        norecord_tv.setVisibility(View.INVISIBLE);
        creatView(record, null);
    }

    /**
     * 创建分页视图
     */
    public void creatView(Records record, ViewGroup viewGroup) {
        MyTextView tvDetail_weight_title = null;
        TextView unit_tv = null;
        tvDetail_weight_title = (MyTextView) findViewById(R.id.weight_textView);
        unit_tv = (TextView) findViewById(R.id.unti_tv);
        if (UtilConstants.CURRENT_USER.getDanwei().equals(UtilConstants.UNIT_FATLB)) {
            tvDetail_weight_title.setTexts(UtilTooth.kgToFloz(record.getRweight()), null);
            if (null != unit_tv) {
                unit_tv.setText(this.getText(R.string.oz_danwei2));
            }
        } else if (UtilConstants.CURRENT_USER.getDanwei().equals(UtilConstants.UNIT_LB)) {
            tvDetail_weight_title.setTexts(UtilTooth.kgToLBoz(record.getRweight()), null);
            if (null != unit_tv) {
                unit_tv.setText(this.getText(R.string.lboz_danwei));
            }
        } else if (UtilConstants.CURRENT_USER.getDanwei().equals(UtilConstants.UNIT_ML2)) {
            tvDetail_weight_title.setTexts(UtilTooth.keep0Point(UtilTooth.kgToML(record.getRweight())) + "", null);
            if (null != unit_tv) {
                unit_tv.setText(this.getText(R.string.ml_danwei2));
            }
        } else if (UtilConstants.CURRENT_USER.getDanwei().equals(UtilConstants.UNIT_ML)) {
            tvDetail_weight_title.setTexts(UtilTooth.keep0Point(record.getRweight()) + "", null);
            if (null != unit_tv) {
                unit_tv.setText(this.getText(R.string.ml_danwei));
            }
        } else {
            tvDetail_weight_title.setTexts(UtilTooth.keep0Point(record.getRweight()) + "", null);
            if (null != unit_tv) {
                unit_tv.setText(this.getText(R.string.g_danwei));
            }
        }
    }




}
